import { fetch } from 'whatwg-fetch';
import { parseParam } from '@/utils/urlUtil';
import ep from '@/utils/eventproxy';
import storejs from 'storejs';

export default function request(url, options, host) {
  //默认设置
  let defaultOptions = {
    method: 'GET',
    mode: 'cors',
    credentials: 'omit',
    params: {},
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      Accept: 'application/json',
      Authorization: storejs.get('token') || '',
    },
  };

  let newOptions = { ...defaultOptions, ...options };
  newOptions.headers = { ...defaultOptions.headers, ...options.headers };

  // 设置url
  url = parseParam(url, options.params);
  // 删除body
  if (newOptions.method == 'GET') delete newOptions.body;

  return fetch(host + url, newOptions)
    .then(async response => {
      var status = response.status;
      var data = await response.json();

      //正常情况 200-300
      if (response.status >= 200 && response.status < 300) {
        var codes = ['10000', '10001', '10002'];
        if (codes.indexOf(data.subCode) != -1) ep.emit('tokenError', data);
        return data;
      }

      // 报错抛出错误 400-500
      if (status >= 400 || status >= 500) {
        const error = new Error();
        error.response = response;
        error.data = data;
        throw error;
      }
    })
    .catch(async e => {
      return {
        code: 503,
        msg: 'Link server timeout',
        subCode: '',
        subMsg: '503',
        timestamp: '',
        data: {},
        verificationFailedMsgList: [],
        success: false,
        fail: true,
      };
    });
}
